const axios = require('axios')
const Boom = require('boom')
const Config = require('../../config').wechat
const WechatUser = require('../../database/models/WechatUser')

const GetSession = function (req, reply) {
  axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${Config.appid}&secret=${Config.secret}&js_code=${req.params.code}&grant_type=authorization_code`)
    .then(function (resp) {
      if (resp.data.errmsg) {
        return reply(Boom.badRequest(resp.data.errmsg))
      }
      WechatUser.set(resp.data.openid, resp.data.session_key, function (err, result1) {
        if (err) {
          return reply(Boom.badImplementation(err))
        }
        WechatUser.initSession(resp.data.openid, function (err, result2) {
          if (err) {
            return reply(Boom.badImplementation(err))
          }
          WechatUser.get(result2.openid, function (err, result3) {
            if (err) {
              return reply(Boom.badImplementation(err))
            }
            reply(result3.session3rd)
          })
        })
      })
    })
}

const Get = function (req, reply) {
  WechatUser.getBySession(req.params.session3rd, function (err, result) {
    if (err) {
      if (err.expires) {
        return reply(false);
      }
      return reply(Boom.badImplementation(err));
    }
    reply(result)
  })
}

module.exports = {
  GetSession,
  Get
}
